# -*- coding: utf-8 -*-
from __future__ import unicode_literals


import rethinkdb as r
from rethinkdb.errors import RqlRuntimeError


def db_conn():
    # https://realpython.com/blog/python/rethink-flask-a-simple-todo-list-powered-by-flask-and-rethinkdb/
    # https://rethinkdb.com/docs/guide/python/
    RDB_HOST =  'localhost'
    RDB_PORT = 28015
    conn = r.connect(RDB_HOST, RDB_PORT).repl()
    db_name = 'blog'
    dbs = r.db_list().run(conn)
    if db_name not in dbs:
        r.db_create(db_name).run(conn)
    tb_name = 'article'
    tbs = r.db(db_name).table_list().run(conn)
    if tb_name not in tbs:
        r.db(db_name).table_create(tb_name).run(conn)
    return (
        r.db(db_name).table(tb_name),
        conn
    )